<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>组织管理-用户管理</title>
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/custom.form.css">
    <style>
        .custom-tree-item-clicked {
            color: #FC9003
        }

        .layui-card {
            overflow-y: auto;
        }

        .layui-card {
            overflow-x: auto;
            height: 620px;
        }

    </style>
</head>
<body>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card" style="height: auto;">
                <div class="layui-card-header"></div>
                <div class="layui-card-body">
                    <!-- 左树 -->
                    <div class="layui-row layui-col-space15">
                        <div class="layui-col-sm12 layui-col-md3">
                            <div class="layui-card">
                                <div class="layui-card-body mini-bar" id="leftTree"></div>
                            </div>
                        </div>
                        <div class="layui-col-sm12 layui-col-md9">
                            <div class="user_table_div">
                                <div class="layui-form-item">
                                    <div class="layui-input-inline">
                                        <input type="text" id="username" class="layui-input" autocomplete="off"
                                               placeholder="请输入账号">
                                    </div>
                                    <div class="layui-input-inline">
                                        <input type="text" id="nickName" class="layui-input" autocomplete="off"
                                               placeholder="请输用户角色名称">
                                    </div>
                                    <div class="layui-input-inline" style="width: auto">
                                        <button class="layui-btn" type="button" onclick="search()">查询</button>
                                        <button class="layui-btn" type="button" onclick="reset()">重置</button>
                                    </div>
                                </div>
                                <table class="layui-hide" id="user_table" lay-filter="user_table"></table>
                            </div>
                        </div>
                    </div>
                    <div id="deptTree" style="display: none"></div>
                    <div id="roles" class="demo-transfer" style="display: none ;padding: 20px 0 0 30px;"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<!--编辑 角色-->
<div id="editRole" style="display: none">
    <form class="layui-form" lay-filter="userForm" style="margin:20px;">
        <!-- 第一行 账号 姓名 -->
        <div class="layui-form-item">
            <label class="layui-form-label">账号</label>
            <div class="layui-input-inline">
                <input type="text" name="swryDm" readonly class="layui-input">
            </div>
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-inline">
                <input type="text" name="swryxm" readonly class="layui-input">
            </div>
        </div>

        <!-- 第二行 人员身份名称 -->
        <div class="layui-form-item">
            <label class="layui-form-label">身份名称</label>
            <div class="layui-input-inline" style="width: 513px;">
                <input id="rysfmc" type="text" name="rysfmc" placeholder="请输入身份名称"
                       required lay-verify="required" class="layui-input">
            </div>
        </div>

        <!-- 第三行 所属税务机关 下拉 -->
        <div class="layui-form-item">
            <label class="layui-form-label">税务机关</label>
            <div class="layui-input-inline" style="width: 513px;">
                <select lay-search="" name="swjgSelect" lay-filter="swjgSelect" id="swjgSelect"></select>
            </div>
        </div>

    </form>
</div>
<!--新增 角色-->
<div id="addRole" style="display: none">
    <form class="layui-form" lay-filter="newuserForm" style="margin:20px;">
        <!-- 第一行 账号 姓名 -->
        <div class="layui-form-item">
            <label class="layui-form-label">账号</label>
            <div class="layui-input-inline">
                <input id="newSwryDm" type="text" name="swryDm" class="layui-input"
                       placeholder="请输入税务人员代码">
            </div>
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-inline">
                <input id="newSwryxm" type="text" name="swryxm" class="layui-input"
                       placeholder="请输入税务人员姓名">
            </div>
        </div>

        <!-- 第二行 人员身份名称 -->
        <div class="layui-form-item">
            <label class="layui-form-label">身份名称</label>
            <div class="layui-input-inline" style="width: 513px;">
                <input id="newRysfmc" type="text" name="rysfmc" placeholder="请输入身份名称"
                       required lay-verify="required" class="layui-input">
            </div>
        </div>

        <!-- 第三行 所属税务机关 下拉 -->
        <div class="layui-form-item">
            <label class="layui-form-label">税务机关</label>
            <div class="layui-input-inline" style="width: 513px;">
                <select lay-search="" name="newswjgSelect" lay-filter="newswjgSelect" id="newswjgSelect"></select>
            </div>
        </div>

    </form>
</div>


<script type="text/html" id="tool">
    <a class="layui-btn layui-btn-xs" lay-event="operationRole">赋予</a>
    <a class="layui-btn layui-btn-xs" lay-event="editRole">编辑</a>
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delRole">删除</a>
    <!--    <a class="layui-btn  layui-btn-xs" lay-event="initPassword">解锁并初始化密码 1 </a>-->
</script>

<script type="text/html" id="toolbar">
    <button class="layui-btn layui-btn-sm" lay-event="addSwry">新增税务人员</button>
    <!--    <button class="layui-btn layui-btn-sm" lay-event="addSwjg">新增税务部门</button>-->
</script>

<script src="/layui/layui.all.js"></script>
<script src="/js/core.util.js"></script>
<script>
    //获取token
    var token = CoreUtil.getData("access_token");
    //地址栏转义token中的#号
    var tokenQuery = token.replace("#", "%23");
    var tableIns1;
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var $ = jQuery = layui.jquery;
    var laydate = layui.laydate;
    var tree = layui.tree;
    var transfer = layui.transfer;
    var deptNo = null;
    var startTime = null;
    var endTime = null;
    layui.use(['table', 'layer', 'laydate', 'tree', 'transfer', 'form'], function () {
        //初始化左侧机关树
        initLeftTree();
        //加载 人员表
        tableIns1 = table.render({
            elem: '#user_table'
            , contentType: 'application/json'
            , headers: {"authorization": token}
            , page: true //开启分页
            , url: '/yhgl/queryYhglData' //数据接口
            , method: 'POST'
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": CoreUtil.isEmpty(res.data) ? 0 : res.data.total, //解析数据长度
                    "data": CoreUtil.isEmpty(res.data) ? null : res.data.records //解析数据列表
                }
            }
            , cols: [
                [
                    {type: 'checkbox', fixed: 'left', align: 'center', sort: true},
                    {field: 'swryDm', title: '账号', width: 140, align: 'center', sort: true},
                    {field: 'swryxm', title: '姓名', width: 140, align: 'center', sort: true},
                    {field: 'rysfDm', title: '身份代码', width: 120, hide: true, align: 'center', sort: true},
                    {field: 'rysfmc', title: '人员身份名称', width: 360, align: 'center', sort: true},
                    {field: 'swjgmc', title: '所属税务机关', width: 300, align: 'center', sort: true},
                    {toolbar: "#tool", title: '操作', width: 220, align: 'center'}
                ]
            ]
            , toolbar: '#toolbar'
        });
        //时间
        laydate.render({
            elem: '#createTime'
            , type: 'datetime'
            , range: '~'
            , done: function (value, date, endDate) {
                if (value !== null && value !== undefined && value !== "") {
                    startTime = value.split("~")[0];
                    endTime = value.split("~")[1];
                } else {
                    startTime = null;
                    endTime = null;
                }
            }
        });
        table.on('toolbar(user_table)', function (obj) {
            switch (obj.event) {
                case 'addSwry':
                    layer.open({
                        type: 1,
                        offset: '50px',
                        skin: 'layui-layer-molv',
                        title: "添加税务人员",
                        area: ['700px', '500px'],
                        shade: 0.6,
                        maxmin: true,
                        shadeClose: true,
                        anim: 0, // 0-6 的动画形式，-1 不开启
                        content: jQuery("#addRole"),
                        btn: ['保存', '取消'],
                        success: function (layero, index) {
                            layero.find('.layui-layer-btn').css('text-align', 'center');
                            // 回显税务机关下拉选
                            CoreUtil.sendPost("/yhgl/queryYhglDataBySwjgDm/" + null, null, function (selectRes) {
                                if (selectRes.code === 0) {
                                    const value = selectRes.data;
                                    let opt = "<option value = ''>请选择科室</option>";
                                    for (let i in value) {
                                        opt += '<option value = "' + value[i].swjgDm + '">' + value[i].swjgmc + '</option>';
                                    }
                                    $("#newswjgSelect").html(opt);
                                    form.render('select'); //需要渲染一下
                                } else {
                                    layer.msg(selectRes.msg);
                                    return false;
                                }
                            });
                        },
                        yes: function (index) {
                            let newswjgSelect = $("#newswjgSelect").val();
                            let rysfmcValue = $("#newRysfmc").val();
                            let mapArr = {
                                "swryDm": $("#newSwryDm").val(),
                                "swryXm": $("#newSwryxm").val(),
                                "rysfDm": null,
                                "rysfmc": rysfmcValue,
                                "swjgDm": newswjgSelect,
                                "swjgmc": $("#newswjgSelect option:selected").text(),
                                "zsfbz": "Y",
                                "ryzt": "Z"
                            }
                            CoreUtil.sendPost("/yhgl/saveYhglData", mapArr, function (resp) {
                                if (resp.code === 0) {
                                    layer.msg("添加成功!");
                                    search();
                                    $('#newSwryDm').val('');
                                    $('#newSwryxm').val('');
                                    $('#newswjgSelect').val('');
                                    form.render('select'); // 重新渲染下拉
                                    $('#newRysfmc').val('');
                                } else {
                                    layer.msg(resp.msg);
                                    search();
                                }
                                return false;
                            });
                            layer.close(index);
                        }
                    });

                    break;
            }
        });
        //赋予、编辑、删除
        table.on('tool(user_table)', function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'del':
                    var userIds = [];
                    userIds.push(data.id);
                    tipDialog(userIds, data.username);
                    break;
                case 'editRole':
                    CoreUtil.sendPost("/yhgl/queryYhglDataBySwryDm/" + data.swryDm, null, function (res) {
                        layer.open({
                            type: 1,
                            offset: '50px',
                            skin: 'layui-layer-molv',
                            title: "编辑角色",
                            area: ['700px', '500px'],
                            shade: 0.6,
                            maxmin: true,
                            shadeClose: true,
                            anim: 0, // 0-6 的动画形式，-1 不开启
                            content: jQuery("#editRole"),
                            btn: ['保存', '取消'],
                            success: function (layero, index) {
                                layero.find('.layui-layer-btn').css('text-align', 'center');
                                // 回显表单数据
                                layui.form.val("userForm", {
                                    "swryDm": res.data.swryDm,        // 账号
                                    "swryxm": res.data.swryxm,        // 姓名
                                    "rysfmc": res.data.rysfmc,        // 人员身份名称
                                });
                                // 回显税务机关下拉选
                                CoreUtil.sendPost("/yhgl/queryYhglDataBySwjgDm/" + res.data.swjgDm, null, function (selectRes) {
                                    if (selectRes.code === 0) {
                                        const value = selectRes.data;
                                        let opt = "<option value = ''>请选择科室</option>";
                                        for (let i in value) {
                                            opt += '<option value = "' + value[i].swjgDm + '">' + value[i].swjgmc + '</option>';
                                        }
                                        $("#swjgSelect").html(opt);
                                        form.render('select'); //需要渲染一下
                                    } else {
                                        layer.msg(selectRes.msg);
                                        return false;
                                    }
                                });
                            },
                            yes: function (index) {
                                let swjgSelect = $("#swjgSelect").val();
                                let rysfmcValue = $("#rysfmc").val();
                                let mapArr = {
                                    "rysfDm": res.data.rysfDm,
                                    "rysfmc": rysfmcValue || res.data.rysfmc,
                                    "swjgDm": swjgSelect || res.data.swjgDm,
                                    "swjgmc": swjgSelect ? $("#swjgSelect option:selected").text() : res.data.swjgmc,
                                    "zsfbz": "Y",
                                    "ryzt": "Z"
                                }
                                CoreUtil.sendPost("/yhgl/updataYhglData", mapArr, function (resp) {
                                    if (resp.code === 0) {
                                        layer.msg("更新成功!");
                                        $('#swjgSelect').val('');
                                        form.render('select'); // 重新渲染下拉
                                        $('#rysfmc').val('');
                                        search();
                                    } else {
                                        layer.msg(resp.msg);
                                        search();
                                    }
                                    return false;
                                });
                                layer.close(index);
                            }
                        });
                    });
                    break;
                case 'initPassword':
                    layer.open({
                        content: '确定要初始化' + data.swryDm + "用户的密码嘛?",
                        yes: function (index, layero) {
                            layer.close(index); //如果设定了yes回调，需进行手工关闭
                            CoreUtil.sendPost("/sys/userinitPassword", data.swryDm, function (res) {
                                layer.msg(res.msg);
                                search()
                            });
                        }
                    });
                    break;
                case 'delRole':
                    console.log("data", data)
                    layer.open({
                        content: '确定要删除' + data.swryxm + "用户么?",
                        yes: function (index, layero) {
                            layer.close(index); //如果设定了yes回调，需进行手工关闭
                            CoreUtil.sendPost("/yhgl/delDataBySwryDm/" + data.rysfDm, null, function (res) {
                                layer.msg(res.msg);
                                search()
                            });
                        }
                    });
                    break;
                case 'operationRole':
                    CoreUtil.sendGet("/sys/user/roles/" + data.rysfDm, null, function (res) {
                        initTransfer(res.data);
                        layer.open({
                            type: 1,
                            offset: '50px',
                            skin: 'layui-layer-molv',
                            title: "赋予角色",
                            area: ['700px', '500px'],
                            shade: 0,
                            maxmin: true,
                            shadeClose: false,
                            content: jQuery("#roles"),
                            btn: ['确定', '取消'],
                            yes: function (index) {
                                //获得右侧数据
                                var roleIds = [];
                                var getData = transfer.getData('ownData');
                                if (getData.length === 0) {
                                    layer.alert("请选择要赋予用户的角色", {
                                        title: "提示", // 标题
                                        icon: 0, // 图标（0: 警告, 1: 成功, 2: 错误）
                                    });
                                    return;
                                } else {
                                    $(getData).each(function (index, item) {
                                        roleIds.push(item.value);
                                    });
                                }
                                CoreUtil.sendPut("/sys/user/roles/" + data.rysfDm, roleIds, function (res) {
                                    layer.msg(res.msg);
                                    search()
                                });
                                layer.close(index);
                            }
                        });
                    });
                    break;
            }
        });
        //删除
        var tipDialog = function (userIds, username) {
            layer.open({
                content: '确定要删除' + username + "用户么?",
                yes: function (index, layero) {
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                    CoreUtil.sendDelete("/sys/user", userIds, function (res) {
                        layer.msg(res.msg);
                        search()
                    });
                }
            });
        };
        form.on('switch(switch)', function () {
            $(".operation_user input[name=status]").attr('type', 'hidden').val(this.checked ? 1 : 2);

        });
        form.on('submit(submit)', function (data) {
            if (data.field.id === undefined || data.field.id === null || data.field.id === "") {
                CoreUtil.sendPost("/sys/user", data.field, function (res) {
                    $(".user_table_div").show();
                    $("#leftTree").show();
                    $(".operation_user").hide();
                    search()
                });
            } else {
                CoreUtil.sendPut("/sys/user", data.field, function (res) {
                    $(".user_table_div").show();
                    $("#leftTree").show();
                    $(".operation_user").hide();
                    search()
                });
            }
            return false;
        });
        //部门树
        var loadDeptTree = function (data) {
            tree.render({
                elem: '#deptTree'
                , data: data
                , onlyIconControl: true  //是否仅允许节点左侧图标控制展开收缩
                , click: function (obj) {
                    selectNode = obj;
                    layer.msg(JSON.stringify(selectNode.data.title));
                }
            });
        };
        var loadLeftTree = function (data) {
            tree.render({
                elem: '#leftTree'
                , data: data
                , onlyIconControl: true  //是否仅允许节点左侧图标控制展开收缩
                , showLine: false  // 是否开启连接线
                , click: function (obj) {
                    console.log(obj)
                    deptNo = obj.data.deptNo;
                    $("#leftTree span").removeClass('custom-tree-item-clicked');     //清除旧的样式
                    $("#leftTree span:contains(" + obj.data.title + ")").addClass('custom-tree-item-clicked');
                    search()
                }
            });
        };
        //部门树点击事件
        $(".operation_user input[name=deptName]").click(function () {
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "选择部门",
                area: ['400px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptTree"),
                btn: ['确定', '取消'],
                yes: function (index) {
                    if (selectNode.data != null) {
                        //选中回显
                        $(".operation_user input[name=deptId]").val(selectNode.data.id);
                        $(".operation_user input[name=deptName]").val(selectNode.data.title);
                    }
                    layer.close(index);
                }
            });
        });

        //初始化左树
        function initLeftTree() {
            CoreUtil.sendGet("/sys/dept/tree", null, function (res) {
                loadLeftTree(res.data);   // 加载左侧树
                loadDeptTree(res.data);   // 加载部门树
            });
        }

        //初始化右树
        var initTransfer = function (data) {
            transfer.render({
                elem: '#roles'
                , data: data.allRole
                , title: ['赋予角色', '拥有角色']
                , showSearch: true
                , value: data.ownRoles
                , id: 'ownData'
                , width: 240 // 设置宽度
                , height: 400 // 设置宽度
                , maxmin: true
                , parseData: function (res) {
                    return {
                        "value": res.id //数据值
                        , "title": res.name //数据标题
                    }
                }
            })
        }
    });

    //执行查询
    function search() {
        //这里以搜索为例
        tableIns1.reload({
            where: { //设定异步数据接口的额外参数，任意设
                swryDm: $("#username").val(),
                swryxm: $("#nickName").val(),
                swjgDm: deptNo
            }
            , page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    }

    function reset() {
        $('#username').val('');
        $('#nickName').val('');
        form.render();
    }


</script>
</body>

</html>